import os

import pandas as pd

day_path = "../data/company-day"


def list_all_files(rootdir):
    """
    列出全部文件
    :param rootdir:
    :return:
    """
    _files = []

    # 列出文件夹下所有的目录与文件
    list_file = os.listdir(rootdir)

    for i in range(0, len(list_file)):
        # 构造路径
        path = os.path.join(rootdir, list_file[i])
        _files.append(path)
    return _files


def list_select_break_average_line():
    """
    选股策略一 突破均线
    :return:
    """
    num = 0
    files = list_all_files(day_path)
    print_flag = True
    total_list = []
    for file in files:
        df = pd.read_csv(file)

        # 常量定义
        MA5 = 'MA5'
        MA20 = 'MA20'
        MA60 = 'MA60'
        # 计算均线
        df[MA5] = df['close'].rolling(5).mean()
        df[MA20] = df['close'].rolling(20).mean()
        df[MA60] = df['close'].rolling(60).mean()
        if print_flag:
            print(df.columns.values.tolist())
            print_flag = False

        tolist = df.values[-1].tolist()
        open = tolist[2]
        high = tolist[3]
        low = tolist[4]
        close = tolist[5]
        ma5 = tolist[-3]
        ma20 = tolist[-2]
        ma60 = tolist[-1]
        if close > open \
                and isHS(tolist[1]) \
                and 15 > close \
                and low < ma60 < ma20 < ma5 < close <= high:
            total_list.append(tolist)
            num += 1

    for li in total_list:
        print(li[0], li[1], li[5], li[18])
    print("选股：", num)
    return total_list


def isHS(code):
    return not str.startswith(code, "sz.30") and not str.startswith(code, "sh.30")


def list_select_sideways_oscillation():
    """
    选股策略二：横盘震荡
    :return:
    """
    company_info = pd.read_csv("../data/a_company_info.csv")
    num = 0
    files = list_all_files(day_path)
    print_flag = True
    title_list = []
    data_list = []
    for file in files:
        df = pd.read_csv(file)
        df = df.tail(80)
        df['MA5'] = df['close'].rolling(5).mean()
        df_max = df.max()
        df_min = df.min()
        low_min = df_min['low']
        high_max = df_max['high']

        avg = (df_min['low'] + df_max['high']) / 2

        ratio_max = (high_max / avg) - 1
        ratio_min = (low_min / avg) - 1

        size_max = df[df['high'] > high_max - 0.3]
        size_min = df[df['low'] < low_min + 0.3]

        max_ratio_min = ratio_max - ratio_min
        if print_flag:
            # print(df.columns.values.tolist(), company_info.columns.values.tolist())
            title_list = df.columns.values.tolist() + company_info.columns.values.tolist()[:]
            print_flag = False
        tolist = df.values[-1].tolist()
        temp = company_info[company_info['code'] == tolist[1]]
        values_tolist = temp.values[-1].tolist()

        if isHS(tolist[1]) and max_ratio_min < 0.35 and 25 > tolist[5] > 7 \
                and 100000000 * 1000 > values_tolist[12] * tolist[5] > 100000000 * 50 \
                and 2 <= len(size_min) < 5 and 2 <= len(size_max) < 5:
            data_list.append(tolist + values_tolist)
            num += 1

    print(title_list[0], title_list[1], title_list[5], title_list[18], title_list[20])
    for li in data_list:
        print(li[0], li[1], li[5], li[18], li[20])

    print("选股：", num)


def list_select_multiple_volume():
    """
    选股策略三：倍量向上
    :return:
    """
    company_info = pd.read_csv("../data/a_company_info.csv")
    num = 0
    files = list_all_files(day_path)
    print_flag = True
    title_list = []
    data_list = []
    for file in files:
        try:
            df = pd.read_csv(file)
            df = df.tail(30)
            df_max = df.max()
            if print_flag:
                title_list = df.columns.values.tolist() + company_info.columns.values.tolist()[:]
                print_flag = False
            tolist = df.values[-1].tolist()
            last2 = df.values[-2].tolist()
            temp = company_info[company_info['code'] == tolist[1]]
            values_tolist = temp.values[-1].tolist()

            multiple = tolist[7] / last2[7]

            price = df_max['close']
            if df_max['open'] > price:
                price = df_max['open']
            # 收盘价大于昨天的最高价
            # 收盘价大于开盘价
            if isHS(tolist[1]) \
                    and last2[5] < tolist[5] == price \
                    and tolist[5] > tolist[2] \
                    and tolist[3] == df_max['high'] \
                    and multiple > 2 \
                    and 15 > tolist[5] > 5:
                data_list.append(tolist + values_tolist)
                num += 1
        except Exception as e:
            pass

    print(title_list[0], title_list[1], title_list[5], title_list[18], title_list[20])
    for li in data_list:
        print(li[0], li[1], li[5], li[18], li[20])

    print("选股：", num)


def list_select_rise_trend():
    """
    选股策略四：脱离均线
    :return:
    """
    company_info = pd.read_csv("../data/a_company_info.csv")
    num = 0
    files = list_all_files(day_path)
    print_flag = True
    title_list = []
    data_list = []
    for file in files:
        df = pd.read_csv(file)
        # 常量定义
        MA5 = 'MA5'
        # 计算均线
        df[MA5] = df['close'].rolling(20).mean()
        if print_flag:
            title_list = df.columns.values.tolist() + company_info.columns.values.tolist()[:]
            print_flag = False
        tolist = df.values[-1].tolist()
        temp = company_info[company_info['code'] == tolist[1]]
        values_tolist = temp.values[-1].tolist()

        tolist = df.values[-1].tolist()
        last2 = df.values[-2].tolist()
        multiple = tolist[7] / last2[7]

        if isHS(tolist[1]) \
                and tolist[5] > tolist[18] \
                and tolist[5] > tolist[2] \
                and tolist[5] == tolist[3] \
                and 15 > tolist[5] > 5 \
                and multiple > 2:
            data_list.append(tolist + values_tolist)
            num += 1

    print(title_list[0], title_list[1], title_list[5], title_list[18], title_list[20])
    for li in data_list:
        print(li[0], li[1], li[5], li[18], li[20])

    print("选股：", num)


def list_select_tread_20_average_line():
    """
    选股策略一 突破均线
    :return:
    """
    num = 0
    files = list_all_files(day_path)
    print_flag = True
    total_list = []
    for file in files:
        df = pd.read_csv(file)
        df = df.tail(30)

        # 常量定义
        MA20 = 'MA20'
        # 计算均线
        df[MA20] = df['close'].rolling(20).mean()
        if print_flag:
            print(df.columns.values.tolist())
            print_flag = False
        tolist = df.values[-1].tolist()
        last2 = df.values[-2].tolist()
        if tolist[5] > tolist[18] \
                and tolist[2] < tolist[5] \
                and tolist[2] > tolist[18] \
                and tolist[4] < tolist[18] \
                and last2[4] < last2[18] \
                and last2[3] > last2[18] \
                and tolist[5] > last2[5] \
                and isHS(tolist[1]) \
                and 15 > tolist[5]:
            total_list.append(tolist)
            num += 1

    for li in total_list:
        print(li[0], li[1], li[5], li[18])

    print("选股：", num)


def list_select_up_20_average_line():
    """
    选股策略一 强势突破
    :return:
    """
    num = 0
    files = list_all_files(day_path)
    print_flag = True
    total_list = []
    for file in files:
        df = pd.read_csv(file)
        df = df.tail(30)

        # 常量定义
        MA20 = 'MA20'
        # 计算均线
        df[MA20] = df['close'].rolling(20).mean()
        if print_flag:
            print(df.columns.values.tolist())
            print_flag = False
        tolist = df.values[-1].tolist()
        if tolist[5] > tolist[18] \
                and tolist[3] == tolist[5] \
                and tolist[2] < tolist[5] \
                and tolist[4] < tolist[18] \
                and isHS(tolist[1]) \
                and 15 > tolist[5]:
            total_list.append(tolist)
            num += 1

    for li in total_list:
        print(li[0], li[1], li[5], li[18])

    print("选股：", num)


def list_select_multiple_volume():
    """
    选股策略三：倍量向上 强势
    :return:
    """
    company_info = pd.read_csv("../data/a_company_info.csv")
    num = 0
    files = list_all_files(day_path)
    print_flag = True
    title_list = []
    data_list = []
    for file in files:
        try:
            df = pd.read_csv(file)
            df = df.tail(20)
            if print_flag:
                title_list = df.columns.values.tolist() + company_info.columns.values.tolist()[:]
                print_flag = False
            tolist = df.values[-1].tolist()
            last2 = df.values[-2].tolist()
            temp = company_info[company_info['code'] == tolist[1]]
            values_tolist = temp.values[-1].tolist()

            multiple = tolist[7] / last2[7]

            # 收盘价大于昨天的最高价
            # 收盘价大于开盘价
            if isHS(tolist[1]) \
                    and last2[5] < tolist[5] \
                    and tolist[5] > tolist[2] \
                    and tolist[3] == tolist[5] \
                    and multiple > 2 \
                    and 15 > tolist[5] > 6:
                data_list.append(tolist + values_tolist)
                num += 1
        except Exception as e:
            pass

    print(title_list[0], title_list[1], title_list[5], title_list[18], title_list[20])
    for li in data_list:
        print(li[0], li[1], li[5], li[18], li[20])

    print("选股：", num)


def list_select_long_lower_lead():
    """
    选股策略三：倍量向上 强势
    :return:
    """
    company_info = pd.read_csv("../data/a_company_info.csv")
    num = 0
    files = list_all_files(day_path)
    print_flag = True
    title_list = []
    data_list = []
    for file in files:
        try:
            df = pd.read_csv(file)
            df = df.tail(20)
            if print_flag:
                title_list = df.columns.values.tolist() + company_info.columns.values.tolist()[:]
                print_flag = False
            tolist = df.values[-1].tolist()
            temp = company_info[company_info['code'] == tolist[1]]
            values_tolist = temp.values[-1].tolist()

            cClose = tolist[5]
            cHigh = tolist[3]
            cOpen = tolist[2]
            cLow = tolist[4]
            cUp = cOpen
            cDown = cOpen
            if cOpen < cClose:
                cUp = cClose
            if cOpen > cClose:
                cDown = cClose
            cDc = cDown - cLow
            cUc = cHigh - cDown
            if isHS(tolist[1]) \
                    and cDc > cUc \
                    and 15 > tolist[5] > 6\
                    and cClose * tolist[8] > 50 * 100000000:
                data_list.append(tolist + values_tolist)
                num += 1
        except Exception as e:
            pass

    print(title_list[0], title_list[1], title_list[5], title_list[18], title_list[20])
    for li in data_list:
        print(li[0], li[1], li[5], li[18], li[20])

    print("选股：", num)


if __name__ == '__main__':
    # 突破均线
    # list_select_break_average_line()
    # 横盘震荡
    # list_select_sideways_oscillation()
    # 翻倍量
    # list_select_multiple_volume()
    # 脱离20日均线
    # list_select_rise_trend()
    # 踩20天线
    # list_select_tread_20_average_line()
    # 突破20天线
    # list_select_up_20_average_line()
    # 强势上涨
    list_select_multiple_volume()
    # 长下引线
    # list_select_long_lower_lead()
